<?php
/** 出租车认证审核
 * Created by PhpStorm.
 * User: chenxiang
 * Date: 2019/9/26
 * Time: 14:56
 */

namespace app\admin\controller;

use my\Security;
use my\Tools;
use think\Request;
use think\Db;
use app\admin\model\RegionModel;
use app\admin\model\AdminActivity;
use DateTime;
use think\Env;

class AuthTaxi extends Base
{
    protected $map = [
        'a.record_status' => ['in', [2, 3]],
        'c.auth_type' => 2
        ];
    protected $region_model;

    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        $this->region_model = new RegionModel();

        $this->region_model = new RegionModel();
        //身份证信息 fr_driver_base =》 check_driver_result
        $this->driverInfo = ['driver_name', 'id_number', 'id_front', 'id_back', 'id_hold'];
        //驾驶证信息 fr_driver_base =》 check_driver_result
        $this->licenseInfo = ['license_time', 'valid_time', 'license'];
        //车辆信息 fr_car =》 check_car_result
        $this->carInfo = ['car_brand', 'car_model', 'car_color', 'body_img'];
        //行驶证信息 fr_car =》 check_car_result
        $this->permitInfo = ['owner', 'car_plate', 'vin', 'register_at', 'permit'];
        //运营证信息
        $this->certificate = ['taxi'];
        //服务资格证信息
        $this->serviceInfo = ['service','service_number','service_valid_time'];
        //监督卡信息
        $this->superviseInfo = ['supervise','supervise_number','supervise_valid_time'];

        $request = Request::instance();
        $domain = $request->domain();
        if (strpos($domain, 'admin') !== false) {
            $btstatus = 2;
        } else {
            $btstatus = 1;
        }
        $this->zhimaBack = $btstatus;

        $where = [
            'parent_id' => 1,
            'region_level' => 1
        ];
        $provinceList = $this->region_model->getRegion($where, 'region_id,region_name');
        $this->assign('provinceList', $provinceList);
    }

    //出租车司机审核列表
    public function index() {
        $page = input('get.page');
        $limit = input('get.limit');

        if($page && $limit) {
            $map = $this->map;
            $get_data = input('get.');

            if ($get_data['car_plate']) {
                $car_plate = $get_data['car_plate'];
                $map['a.car_plate'] = Security::encrypt($car_plate);
            }
            if ($get_data['driver_phone']) {
                $phone = $get_data['driver_phone'];
                $map['b.driver_phone'] = Security::encrypt($phone);
            }
            //注册省份
            if ($get_data['province_id'] != '') {
                $map['c.work_province'] = $get_data['province_id'];
            }
            //注册城市
            if ($get_data['city_id'] != '') {
                $map['c.work_city'] = $get_data['get.city_id'];
            }

            $res = Db::name('car_info a')
                ->join('driver_base b', 'a.driver_id=b.driver_id', 'LEFT')
                ->join('driver_info c', 'b.driver_id=c.driver_id', 'LEFT')
                ->join('driver_back d', 'a.driver_id=d.driver_uid', 'LEFT')
                ->join('xm_region e', 'c.work_province=e.region_id', 'LEFT')
                ->join('xm_region f', 'c.work_city=f.region_id', 'LEFT')
                ->field('a.record_status,a.car_id,a.driver_id,b.driver_name,b.driver_phone,c.auth_type,a.car_plate,a.car_brand,a.car_model,a.color,a.register_at,a.add_time,a.reason,b.auth_status,c.id_number,d.backStatus,a.car_number,c.register_city,e.region_name region_name_province,f.region_name region_name_city,a.car_vin,a.code')
                ->where($map)
                ->page($page, $limit)
                ->order('a.record_status asc,a.car_id desc')
                ->select();

            $count = Db::name('car_info a')
                ->join('driver_base b', 'a.driver_id=b.driver_id', 'LEFT')
                ->join('driver_info c', 'b.driver_id=c.driver_id', 'LEFT')
                ->where($map)
                ->count();

            $res = decode_array_2($res);
            return json([
                'code' => 0,
                'msg' => '',
                'limit' => $limit,
                'count' => $count,
                'data' => $res
            ]);
        }

        return $this->fetch();
    }

    //司机认证编辑
    public function edit()
    {
        if (input('post.')) {
            $postInfo = input('post.');
            $driverInfo = [
                'driver_name' => $postInfo['driver_name'],
            ];
            Db::name("driver_base")->where('driver_id', $postInfo['driver_id'])->update($driverInfo);
            $driverBseInfo = [
                'id_number' => Security::encrypt($postInfo['id_number']),
                'valid_time' => strtotime($postInfo['valid_time']),
                'license_time' => strtotime($postInfo['license_time']),
                'id_front' => Security::encrypt($postInfo['id_front']),
                'id_back' => Security::encrypt($postInfo['id_back']),
                'license' => Security::encrypt($postInfo['license']),
                'permit' => Security::encrypt($postInfo['permit']),
                'body_img' => Security::encrypt($postInfo['body_img']),
                'supervise' => Security::encrypt($postInfo['supervise']),
                'supervise_number' => Security::encrypt($postInfo['supervise_number']),
                'service' => Security::encrypt($postInfo['service']),
                'service_number' => Security::encrypt($postInfo['service_number'])
            ];
            Db::name("driver_info")->where('driver_id', $postInfo['driver_id'])->update($driverBseInfo);
            $carInfo = [
                'car_plate' => Security::encrypt($postInfo['car_plate']),
                'color' => Security::encrypt($postInfo['color']),
                'owner' => Security::encrypt($postInfo['owner']),
                'vin' => Security::encrypt($postInfo['vin']),
                'car_vin' => Security::encrypt($postInfo['car_vin']),
                'register_at' => strtotime($postInfo['register_at']),
                'update_time' => time()
            ];
            Db::name("car_info")->where('car_id', $postInfo['car_id'])->update($carInfo);
            return "<script type='application/javascript'>alert('修改成功');parent.window.location.reload();</script>";
        } else {
            $car_id = input('get.car_id');
            if ($car_id > 0) {
                $info = Db::name('car_info a')
                    ->join('driver_base b', 'a.driver_id=b.driver_id', 'LEFT')
                    ->join('driver_info c', 'b.driver_id=c.driver_id', 'LEFT')
                    ->field('a.car_id,a.driver_id,b.driver_name,c.id_number,c.license_time,c.valid_time,a.color,a.owner,a.car_plate,a.vin,a.car_vin,a.register_at,c.id_front,c.id_back,c.license,a.permit,a.body_img,c.supervise,c.supervise_number,c.service,c.service_number')
                    ->where('a.car_id', $car_id)
                    ->find();
                $info = decode_array($info);

                $info['car_vin'] = Security::decrypt($info['car_vin']);
                $info['supervise'] = Security::decrypt($info['supervise']);
                $info['supervise_number'] = Security::decrypt($info['supervise_number']);
                $info['service'] = Security::decrypt($info['service']);
                $info['service_number'] = Security::decrypt($info['service_number']);
                $this->assign('info', $info);
            }
        }
        return $this->fetch();
    }

    //司机认证待审核显示
    public function auth()
    {
        $car_id = input('get.car_id');
        if ($car_id > 0) {
            $info = Db::name('car_info a')
                ->join('driver_base b', 'a.driver_id=b.driver_id', 'LEFT')
                ->join('driver_info c', 'b.driver_id=c.driver_id', 'LEFT')
                ->join('driver_back d', 'a.driver_id=d.driver_uid', 'LEFT')
                ->join('region e', 'c.work_province=e.region_id', 'LEFT')
                ->join('region f', 'c.work_city=f.region_id', 'LEFT')
                ->field('a.record_status,b.driver_name,c.id_number,c.id_front,c.id_back,c.id_hold,c.license_time,c.valid_time,c.license,a.car_brand,a.car_model,a.color,a.body_img,a.owner,a.car_plate,a.vin,a.car_vin,a.register_at,a.permit,b.check_driver_result,a.check_car_result,b.auth_status,c.driver_id,a.taxi,a.taxi_certificate,c.auth_type,c.register_city,a.seats,a.company,d.backStatus,d.resultContent,d.time,a.reason,a.car_number,e.region_name as region_name_province,f.region_name as region_name_city,a.code,a.comm_pass,a.sail_pass,a.car_insurance,a.time,a.errorCode,a.errorMsg,supervise,supervise_pic_status,supervise_thumb,supervise_number,supervise_valid_time,service,service_pic_status,service_thumb,service_number,service_valid_time')
                ->where('a.car_id', $car_id)
                ->find();
            $info = decode_array($info);
            $info['supervise'] = Security::decrypt($info['supervise']);
            $info['supervise_number'] = Security::decrypt($info['supervise_number']);
            $info['service'] = Security::decrypt($info['service']);
            $info['service_number'] = Security::decrypt($info['service_number']);

            $info['auth_type'] = auth_type()[$info['auth_type']];
            $info['resultContent'] = !empty($info['resultContent']) ? explode(',', $info['resultContent']) : '';
            $info['time'] = !empty($info['time']) ? date("Y-m-d H:i:s", $info['time']) : '';
            if ($info['record_status'] != 1) {
                $info['check_driver_result'] = explode(',', $info['check_driver_result']);
                $info['check_car_result'] = explode(',', $info['check_car_result']);
                $check_arr = array_merge($info['check_driver_result'], $info['check_car_result']);
                $check = [
                    'driverInfo' => 0,   //身份信息
                    'licenseInfo' => 0,   //驾驶证信息
                    'carInfo' => 0,   //车辆信息
                    'permitInfo' => 0,   //行驶证信息
                    'driverDataCheck' => 0, //司机背景资料
                ];
                //身份信息
                if (in_array('id_number', $check_arr) && in_array('driver_name', $check_arr) && in_array('id_front', $check_arr) && in_array('id_back', $check_arr) && in_array('id_hold', $check_arr)) {
                    $check['driverInfo'] = 1;
                }
                //驾驶证信息
                if (in_array('license_time', $check_arr) && in_array('valid_time', $check_arr) && in_array('license', $check_arr)) {
                    $check['licenseInfo'] = 1;
                }
                //车辆信息
                if (in_array('car_brand', $check_arr) && in_array('car_model', $check_arr) && in_array('car_color', $check_arr) && in_array('body_img', $check_arr)) {
                    $check['carInfo'] = 1;
                }
                //行驶证信息
                if (in_array('owner', $check_arr) && in_array('car_plate', $check_arr) && in_array('register_at', $check_arr) && in_array('permit', $check_arr) && in_array('vin', $check_arr)) {
                    $check['permitInfo'] = 1;
                }
                //司机背景资料
                if (in_array('driverDataCheck', $check_arr)) {
                    $check['driverDataCheck'] = 1;
                }

                //监督卡信息
                if (in_array('supervise', $check_arr) && in_array('supervise_number', $check_arr) && in_array('supervise_valid_time', $check_arr)) {
                    $check['superviseInfo'] = 1;
                }

                //服务资格证信息
                if (in_array('service', $check_arr) && in_array('service_number', $check_arr) && in_array('service_valid_time', $check_arr)) {
                    $check['serviceInfo'] = 1;
                }

//                //营运车辆运输证与服务资格证
//                if (in_array('taxi', $check_arr) && in_array('taxi_certificate', $check_arr)) {
//                    $check['certificate'] = 1;
//                }
                //营运车辆运输证信息
                if (in_array('taxi', $check_arr)) {
                    $check['certificate'] = 1;
                }

                //车险背调信息操作
                if (!empty($info['code']) && $info['code'] == 200) {
                    $info['car_insurance'] = json_decode($info['car_insurance'], true);
                }
                $config['info'] = $info;
                $config['check'] = $check;
                $config['car_id'] = $car_id;
                $config['car_check_info'] = config('taxi_check_info');
                $this->assign($config);
            }
        }
        return $this->fetch();
    }

    //司机认证审核提交
    public function ajax_submits()
    {
        $post_car_data = input('post.');     //post获取参数
        $arr = explode('&', $post_car_data['data']);//转成数组
        $post_car = array();
        foreach ($arr as $k => $v) {
            $arr = explode('=', $v);
            $post_car[$arr[0]] = $arr[1];
        }
        //查询车辆信息
        $driver_car_info = Db::name('car_info a')
            ->join('driver_base b', 'a.driver_id=b.driver_id', 'LEFT')
            ->join('driver_info c', 'b.driver_id=c.driver_id', 'LEFT')
            ->field('b.driver_name,b.driver_phone,a.car_plate,a.car_vin,a.driver_id,c.registration_id,b.check_driver_result')
            ->where('a.car_id', $post_car['car_id'])->find();
        $driver_car_info = decode_array($driver_car_info);
        //更新车辆信息数据 审核结果
        Db::name('car_info')->where('car_id', $post_car['car_id'])->update(['record_status' => $post_car['record_status'], 'reason' => !empty($post_car['reason']) ? $post_car['reason'] : '']);
        //只有第一辆车的时候更新状态
        //$count = Db::name('car_info')->where('driver_id',$post_car['driver_id'])->count();
//        //司机状态有变化时，则更新
//        $check_driver_result_arr = array_merge($this->driverInfo, $this->licenseInfo, ['driverDataCheck'],$this->superviseInfo, $this->serviceInfo);
//        $check_driver_result = explode(',', $driver_car_info['check_driver_result']);
//        $diff = array_diff($check_driver_result_arr, $check_driver_result);
//        if (!empty($diff)) {
//            Db::name('driver_base')->where("driver_id", $post_car['driver_id'])->update(['auth_status' => 3]);
//        } else {
//            Db::name('driver_base')->where("driver_id", $post_car['driver_id'])->update(['auth_status' => 1, 'check_pass_time' => time()]);
//        }
        //通过审核
        if ($post_car['record_status'] == 2) {
            //$this->error('请重新审核提交', '', '', 1);
            return json(['status' => 0, 'msg' => '请重新审核提交']);
        }
        $title = $content = '';
        if ($post_car['record_status'] == 1) {
            //更新司机状态 为通过
            Db::name('driver_base')->where("driver_id", $post_car['driver_id'])->update(['auth_status' => 1, 'check_pass_time' => time()]);
            $data_auth_record['result'] = 1;
            Db::name('driver_base')->where('driver_id', $post_car['driver_id'])->update(['first_pass' => 1]);
            //if(!empty($driver_car_info['car_vin'])){
            //修改车辆在险信息
            //    Db::table('xm_car_info')->where('car_id',$post_car['car_id'])->update(['comm_pass'=>1,'sail_pass'=>1]);
            //}
            $title = "审核通知";
            $content = "恭喜您，车主:{$driver_car_info['driver_name']},车牌:{$driver_car_info['car_plate']},您的认证申请已审核通过，请尽快完善营运证及保单资料，审核通过后即可立即接单";
            $info = ['type' => 'user', 'registration_id' => $driver_car_info['registration_id'], 'uid' => $driver_car_info['driver_id']];
            sendjg($info, $title, $content, 1);
            Tools::sendMes($driver_car_info['driver_phone'], '', 99);
        } else if ($post_car['record_status'] == 3) {
            //更新司机状态为 不通过
            Db::name('driver_base')->where("driver_id", $post_car['driver_id'])->update(['auth_status' => 3]);
            $data_auth_record['result'] = 2;
            $data_auth_record['reason'] = Tools::mb_truncate($post_car['reason'], 0, 80, '');
            $title = "审核通知";
            $content = "车主:{$driver_car_info['driver_name']},车牌:{$driver_car_info['car_plate']},您的车审核未通过,原因:{$post_car['reason']}";
            //Tools::JPush($title,$content,$driver_car_info['registration_id']);
            $info = array('type' => 'user', 'registration_id' => $driver_car_info['registration_id'], 'uid' => $driver_car_info['driver_id']);
            sendjg($info, $title, $content, 1);
            Tools::sendMes($driver_car_info['driver_phone'], '', 23);
        }
        //更新driver_info表 司机服务分
        $data_driver['service_score'] = config('default_score')['driver_service_score'];
        db('driver_info')->where('driver_id', $data_driver['driver_id'])->update(['service_score' => $data_driver['service_score']]);
        //审核记录
        $data_auth_record['car_id'] = $post_car['car_id'];
        $data_auth_record['driver_id'] = $driver_car_info['driver_id'];
        $data_auth_record['add_time'] = time();
        $data_auth_record['admin_id'] = $_SESSION['admin_id'];
        $data_message['record_id'] = db('driver_auth_record')->insertGetId($data_auth_record);//关联消息表
        //审核记录信息
        $data_message['mes_type'] = 1;//审核通知
        $data_message['title'] = $title;//信息标题
        $data_message['content'] = $content;//信息内容
        $data_message['send_time'] = time();//发送时间
        $data_relation['mes_id'] = Db::name('driver_message')->insertGetId($data_message);//保存信息
        $data_relation['driver_id'] = $driver_car_info['driver_id'];
        db('driver_mes_relation')->insert($data_relation);//保存信息和司机之间的关系
        return json(['status' => 1, 'msg' => '操作成功']);
    }

    //审核某个字段
    public function check_one()
    {
        $name = input('post.name');
        $value = input('post.value');
        $car_id = input('post.car_id');
        $carInfo = Db::name('car_info')->where('car_id', $car_id)->find();
        //身份证信息 fr_driver_base =》 check_driver_result
        if ($name == 'driverInfo') {
            $str = $this->driverInfo;
        }
        //驾驶证信息 fr_driver_base =》 check_driver_result
        if ($name == 'licenseInfo') {
            $str = $this->licenseInfo;
        }
        //车辆信息 fr_car =》 check_car_result
        if ($name == 'carInfo') {
            $str = $this->carInfo;
        }
        //行驶证信息 fr_car =》 check_car_result
        if ($name == 'permitInfo') {
            $str = $this->permitInfo;
        }
        //运营证信息
        if ($name == 'certificate') {
            $str = $this->certificate;
        }
        //服务资格证
        if ($name == 'serviceInfo') {
            $str = $this->serviceInfo;
        }
        //监督卡
        if ($name == 'superviseInfo') {
            $str = $this->superviseInfo;
        }
//        //保单信息
//        if ($name == 'insurance') {
//            $str = $this->insurance;
//        }
        //司机背景资料信息
        if ($name == 'driverDataCheck') {
            $str = ['driverDataCheck'];
        }
        //身份证信息 + 驾驶证信息 =》 fr_driver_base =》 check_driver_result
        if (in_array($name, ['driverInfo', 'licenseInfo', 'driverDataCheck','serviceInfo','superviseInfo'])) {
            $driverBaseInfo = Db::name('driver_base')->where('driver_id', $carInfo['driver_id'])->find();
            $checkDriver = $driverBaseInfo['check_driver_result'] ? explode(',', $driverBaseInfo['check_driver_result']) : [];
            if ($value == 1) {
                $check_value = $checkDriver ? array_merge($str, $checkDriver) : $str;
            } else {
                $check_value = array_diff($checkDriver, $str);
            }
            $data['check_driver_result'] = implode(',', $check_value);
            switch ($name) {
                case 'licenseInfo':
                    if ($value == 1) {
                        $license_pic_status = 1;
                    } else {
                        $license_pic_status = 3;
                    }
                    Db::name('driver_info')->where('driver_id', $carInfo['driver_id'])->update(['license_pic_status' => $license_pic_status]);
                    break;
                case 'superviseInfo':
                    if ($value == 1) {
                        $supervise_pic_status = 1;
                    } else {
                        $supervise_pic_status = 3;
                    }
                    Db::name('driver_info')->where('driver_id', $carInfo['driver_id'])->update(['supervise_pic_status' => $supervise_pic_status]);
                    break;
                case 'serviceInfo':
                    if ($value == 1) {
                        $service_pic_status = 1;
                    } else {
                        $service_pic_status = 3;
                    }
                    Db::name('driver_info')->where('driver_id', $carInfo['driver_id'])->update(['service_pic_status' => $service_pic_status]);
                    break;
            }

//            if ($name == 'licenseInfo') {
//                if ($value == 1) {
//                    $license_pic_status = 1;
//                } else {
//                    $license_pic_status = 3;
//                }
//                Db::name('driver_info')->where('driver_id', $carInfo['driver_id'])->update(['license_pic_status' => $license_pic_status]);
//            }
            Db::name('driver_base')->where('driver_id', $carInfo['driver_id'])->update($data);
        } elseif (in_array($name, ['carInfo', 'permitInfo', 'certificate'])) {//车辆信息 + 行驶证信息 + 运营证信息fr_car =》 check_car_result
            $check_value = $carInfo['check_car_result'] ? explode(',', $carInfo['check_car_result']) : [];
            if ($value == 1) {
                $check_value = $check_value ? array_merge($str, $check_value) : $str;
            } else {
                $check_value = array_diff($check_value, $str);
            }
            $result = ['check_car_result' => implode(',', $check_value)];
            //运营证信息
            if ($name == 'certificate') {
                if ($value == 1) {
                    $result['taxi_pass'] = 1;
                    $result['taxi_certificate_pass'] = 1;
                } else {
                    $result['taxi_pass'] = 3;
                    $result['taxi_certificate_pass'] = 3;
                }
            }
//            //保险单信息
//            if ($name == 'insurance') {
//                if ($value == 1) {
//                    $result['comm_pass'] = 1;
//                    $result['sail_pass'] = 1;
//                    $result['carriage_pass'] = 1;
//                } else {
//                    $result['comm_pass'] = 3;
//                    $result['sail_pass'] = 3;
//                    $result['carriage_pass'] = 3;
//                }
//            }
            Db::name('car_info')->where('car_id', $car_id)->update($result);
        } else { //监督卡 + 服务资格证
            //出租车更新运营证，快车不更新
            $auth_type = Db::name('driver_info')->where('driver_id', $carInfo['driver_id'])->getField('auth_type');
            if ($auth_type == 2) {//出租车
                if ($value == 1) {
                    Db::name('driver_base')->where('driver_id', $carInfo['driver_id'])->update(['check_driver_result' => implode(',', array_merge($this->driverInfo, $this->licenseInfo, ['driverDataCheck'],  $this->serviceInfo, $this->superviseInfo))]);
                    Db::name('car_info')->where('car_id', $car_id)->update(['check_car_result' => implode(',', array_merge($this->carInfo, $this->permitInfo, $this->certificate))]);
                    $result['taxi_pass'] = 1;
//                    $result['taxi_certificate_pass'] = 1; // 该字段数据表 已废弃
                } else {
                    Db::name('driver_base')->where('driver_id', $carInfo['driver_id'])->update(['check_driver_result' => '']);
                    Db::name('car_info')->where('car_id', $car_id)->update(['check_car_result' => '']);
                    $result['taxi_pass'] = 3;
//                    $result['taxi_certificate_pass'] = 3;
                }
                Db::name('car_info')->where('car_id', $car_id)->update($result);
                //快车，不更新运营证
            } else {
                if ($value == 1) {
                    //只有第一辆车更新司机信息
                    Db::name('driver_base')->where('driver_id', $carInfo['driver_id'])->update(['check_driver_result' => implode(',', array_merge($this->driverInfo, $this->licenseInfo, ['driverDataCheck'],  $this->serviceInfo, $this->superviseInfo))]);
                    Db::name('car_info')->where('car_id', $car_id)->update(['check_car_result' => implode(',', array_merge($this->carInfo, $this->permitInfo))]);
                } else {
                    Db::name('driver_base')->where('driver_id', $carInfo['driver_id'])->update(['check_driver_result' => '']);
                    Db::name('car_info')->where('car_id', $car_id)->update(['check_car_result' => '']);
                }
            }
        }
        echo json_encode(['code' => 1]);
    }


    //处理时间
    public function date_teim_infomation($time = '', $type = 1)
    { //1时间戳2日期
        if ($type == 1) {
            $obj = new DateTime('@' . $time); // 这里时间戳前要写一个@符号
            $timezone = timezone_open('Asia/HONG_KONG'); // 设置时区
            $obj->setTimezone($timezone);
            return $obj->format("Y-m-d");
        } else {
            $obj = new DateTime($time);
            return $obj->format("U");
        }
    }


}